<template>
  <div class="push-down-content" v-loading="pageLoading">
    <el-form label-width="140px" ref="orderInfo" :model="orderInfo" class="table_form_wrap">
      <!-- 基本信息 -->
      <el-card class="sourcing-form-card" shadow="never">
        <div slot="header">
          <span>基本信息</span>
        </div>
        <el-row class="box">
          <el-col :span="8">
            <el-form-item label="制单人：">
              <el-input v-model="orderInfo.creatorName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="期望到货时间：">
              <el-date-picker
                v-model="orderInfo.expectArrivalDate"
                type="date"
                placeholder="期望到货时间"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购订单类型：">
              <el-select
                v-model="orderInfo.orderType"
                @change="selectOrderType"
                collapse-tags
                placeholder="请选择"
              >
                <el-option
                  v-for="item in orderTypeOptions"
                  :key="item.orderType"
                  :label="item.orderTypeName"
                  :value="item.orderType"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注(我司)：">
              <el-input
                v-model.trim="orderInfo.mark"
                placeholder="输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注(供应商)：">
              <el-input
                v-model.trim="orderInfo.supplierMark"
                placeholder="输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="询价单号：">
              <el-input v-model="orderInfo.billNum" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否囤货：">
              <el-input v-model="orderInfo.isStoreGoodsStr" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="囤货说明：">
              <el-input type="textarea" rows="1" v-model="orderInfo.storeGoodsReason" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <!-- 供应商信息 -->
      <el-card class="sourcing-form-card" shadow="never">
        <div slot="header">
          <span>供应商信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商代码：">
              <el-input v-model="orderInfo.supplierNum" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称：">
              <el-input v-model="orderInfo.supplierName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票供应商：">
              <el-select
                v-model="orderInfo.billSupplierId"
                @change="selectBillSupplier"
                collapse-tags
                placeholder="请选择开票供应商"
              >
                <el-option
                  v-for="item in billSupplierList"
                  :key="item.billSupplierId"
                  :label="item.billSupplierName"
                  :value="item.billSupplierId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票类型：">
              <el-input v-model.trim="orderInfo.invoiceTypeStr" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率：">
              <el-input v-model.trim="orderInfo.taxRateStr" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <!-- 物流信息 -->
      <el-card class="sourcing-form-card" shadow="never">
        <div slot="header">
          <span>物流信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="收货公司：">
              <el-select
                v-model="orderInfo.receiveCompanyId"
                @change="selectReceiveCompany"
                filterable
                placeholder="选择收货公司"
              >
                <el-option
                  v-for="item in companyOptions"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货物处理方式：">
              <el-select
                clearable
                v-model="orderInfo.treatmentMethodId"
                collapse-tags
                placeholder="选择货物处理方式"
              >
                <el-option
                  v-for="item in processTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="showBackCompany">
            <el-form-item label="转回公司：">
              <el-select
                v-model="orderInfo.backCompanyId"
                @change="selectBackCompany"
                filterable
                placeholder="选择转回公司"
              >
                <el-option
                  v-for="item in companyOptions"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发货要求：">
              <el-select
                v-model="orderInfo.deliveryDemand"
                placeholder="选择发货要求"
              >
                <el-option
                  v-for="item in deliveryDemandOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货地址详情：">
              <el-input
                v-model="orderInfo.receiveAddressInfor"
                placeholder="输入收货地址详情"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否现场接货：">
              <el-input
                readonly
                :value="orderInfo.isScenePickupStr"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="能否直接联系客户：">
              <el-input
                readonly
                :value="orderInfo.isDirectContactStr"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <!-- 结算信息 -->
      <el-card class="sourcing-form-card" shadow="never">
        <div slot="header">
          <span>结算信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="结算公司：">
              <el-select
                clearable
                v-model="settleCompany"
                style="width: 100%"
              >
                <el-option
                  v-for="option in settleCompanyList"
                  :key="option.settlementCompanyId"
                  :value="option.settlementCompanyId"
                  :label="option.settlementCompanyName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费承担方：">
              <el-input v-model="orderInfo.freightPayerStr" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费金额：">
              <el-input
                v-model.trim="orderInfo.freightPrice"
                @input="limitInput($event, 'freightPrice')"
                v-if="orderInfo.freightPayer == 40357"
                placeholder="输入运费金额"
              />
              <el-input
                v-model.trim.number="orderInfo.freightPrice"
                v-else
                disabled
                placeholder="输入运费金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <!-- 商品信息 -->
      <el-card class="sourcing-form-card" shadow="never">
        <el-row slot="header">
          <span>商品信息</span>
        </el-row>
        <el-row>
          <BasicList
            :showSelectCol="false"
            :maxTableHeight="500"
            :data-source="orderInfo.winBiddingVOList"
            :columns="ORDER_INFO_TABLE_COLUMNS"
            :show-pagination="false"
            :showActionCol="false"
          />
          <el-row type="flex" justify="center" class="operate-area">
            <el-button
              type="primary"
              :loading="submitLoading"
              @click="handleConfirm"
            >确定</el-button>
          </el-row>
        </el-row>
      </el-card>
    </el-form>
    <PushSuccessDialog
      purchaseType="self"
      :visible.sync="successDialogVisible"
      :purchase-order-no="purchaseOrderNo"
    />
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import BasicList from '@/components/skusTable';
import PushSuccessDialog from '@sourcing/purchase-inquiry/components/GeneratedSuccess';
import { ORDER_TIMEOUT_REASON_OPTION } from '@/pages/sourcing/constants';
import {
  submitSelfPurchaseOrderService
} from '@api/sourcing/selfPurchaseInquiry';
import {
  getWinOrderInfoService,
  getSettlementCompanyService
} from '@api/sourcing/purchaseInquiry';
import { ORDER_INFO_TABLE_COLUMNS } from '../constants';

export default {
  name: 'Index',
  components: {
    BasicList,
    PushSuccessDialog
  },
  data () {
    return {
      ORDER_INFO_TABLE_COLUMNS,
      orderInfo: {},
      pageLoading: false,
      submitLoading: false,
      ORDER_TIMEOUT_REASON_OPTION,
      successDialogVisible: false,
      purchaseOrderNo: '',
      billSupplierList: [], // 开票供应商
      processTypeOptions: [], // 货物处理方式字典
      companyOptions: [], // 公司
      orderTypeOptions: [], // 采购订单类型
      settleCompany: '',
      // 结算公司列表
      settleCompanyList: [],
      // 发货要求
      deliveryDemandOptions: [
        { label: '有货先发', value: 1 },
        { label: '货齐再发', value: 2 }
      ],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
    };
  },
  computed: {
    supplierId () {
      return this.$route.query.supplierId
    },
    sourcingSupplierId () {
      return this.$route.query.sourcingSupplierId
    },
    // 是否显示转回公司
    showBackCompany () {
      // 货物处理方式 18907 厂家直送 18908 转回分公司 2001 转至其他分公司自提 2002 转至其他分公司配送
      return [18908, 2001, 2002].includes(this.orderInfo.treatmentMethodId)
    },
  },
  watch: {
    settleCompanyList: {
      handler (newVal, oldVal) {
        if (newVal.length === 1) {
          this.settleCompany = newVal[0].settlementCompanyId
        }
      },
      deep: true
    }
  },
  mounted () {
    // 单据详情信息
    this.getWinOrderInfo();
    // 货物处理方式
    this.querySysTypeInfoList();
    // 转回公司
    this.queryCompanyList();
    // 查询开票供应商
    this.queryBillingSupplierList();
    // 采购订单类型
    this.queryPurchaseOrderTypes();
  },
  methods: {
    ...mapActions('sourcing/purchaseInquiry', [
      'getSysTypeInfoList', // 获取 货物处理方式
      'getSonCompanyList', // 收货公司转回公司
      'queryBillSupplierList', // 查询开票供应商
      'getWinSourcingSKUInforList', // 详情信息
      'getSysDictByTypeList', // 采购订单类型
    ]),
    // 获取单据详情
    async getWinOrderInfo () {
      const data = {
        sourcingSupplierId: this.sourcingSupplierId,
        type: 1,
      };
      const res = await getWinOrderInfoService(
        data,
        state => { this.pageLoading = state }
      )
      if (res) {
        const { settleCompanyList } = res.data;
        this.orderInfo = res.data;
        this.settleCompanyList = settleCompanyList;
      }
    },
    // 获取结算公司
    async getSettlementCompanyListAction () {
      this.settleCompany = '';
      const {
        receiveCompanyId,
        orderType
      } = this.orderInfo;
      const data = {
        supplierId: this.supplierId,
        receivingCompanyId: receiveCompanyId,
        orderType,
      }
      const res = await getSettlementCompanyService(data)
      if (res) {
        this.settleCompanyList = res.data || []
      }
    },
    // 获取货物处理方式
    querySysTypeInfoList () {
      const cb = (res) => {
        if (res?.data) {
          this.processTypeOptions = res.data.map(item => {
            return {
              value: item.sysTypeId,
              code: item.sysTypeCode,
              label: item.sysTypeName,
              disabled: item.sysTypeId == 18907 // 自进货不能选择厂家直送
            }
          });
        }
      };
      const data = {};
      this.getSysTypeInfoList({
        payload: {
          data,
          cb
        }
      });
    },
    // 查询公司列表 供收货公司 转回公司是用
    queryCompanyList () {
      const cb = (res) => {
        if (res?.data) {
          this.companyOptions = res.data.map(item => {
            return {
              companyId: item.companyId,
              companyName: item.companyName,
              companyCode: item.companyCode,
              companyAddress: item.companyAddress,
            }
          });
        }
      };
      this.getSonCompanyList({
        payload: {
          data: {},
          cb
        }
      });
    },
    // 查询开票供应商
    queryBillingSupplierList () {
      const cb = (res) => {
        if (res?.data.results) {
          this.billSupplierList = res.data.results.map(item => {
            return {
              billSupplierId: Number(item.invoiceSupplierId),
              billSupplierName: item.invoiceSupplierName,
              billSupplierCode: item.invoiceSupplierCode
            };
          });
        }
      };
      this.queryBillSupplierList({
        payload: {
          data: { supplierId: this.supplierId },
          cb
        }
      });
    },
    // 获取采购订单类型
    queryPurchaseOrderTypes () {
      const cb = (res) => {
        if (res?.data) {
          this.orderTypeOptions = res.data.map(item => {
            return {
              orderType: item.sysTypeId,
              orderTypeName: item.sysTypeName
            }
          });
        }
      };
      this.getSysDictByTypeList({
        payload: {
          data: { sysTypeClassId: 10051 },
          cb
        }
      });
    },
    // 选择收货公司
    selectReceiveCompany (val) {
      this.companyOptions.map((item) => {
        if (item.companyId == val) {
          this.orderInfo.receiveCompanyId = item.companyId;
          this.orderInfo.receiveCompanyName = item.companyName;
          this.orderInfo.receiveCompanyNum = item.companyCode;
          this.orderInfo.receiveAddressInfor = item.companyAddress;
        }
      });
      this.getSettlementCompanyListAction()
    },
    // 选择转回公司
    selectBackCompany (val) {
      this.companyOptions.map((item) => {
        if (item.companyId == val) {
          this.orderInfo.backCompanyId = item.companyId;
          this.orderInfo.backCompanyName = item.companyName;
          this.orderInfo.backCompanyNum = item.companyCode;
        }
      });
    },
    // 选择开票供应商
    selectBillSupplier (val) {
      this.billSupplierList.map((item) => {
        if (item.billSupplierId == val) {
          this.orderInfo.billSupplierId = item.billSupplierId;
          this.orderInfo.billSupplierName = item.billSupplierName;
          this.orderInfo.billSupplierCode = item.billSupplierCode;
        }
      });
    },
    // 选择 采购类型
    selectOrderType (val) {
      this.orderInfo.orderType = val;
      this.orderTypeOptions.map((item) => {
        if (item.orderType == val) {
          this.orderInfo.orderTypeName = item.orderTypeName;
        }
      });
      this.getSettlementCompanyListAction()
    },
    // 确定提交
    handleConfirm () {
      const {
        backCompanyId,
        orderType,
        deliveryDemand,
        receiveCompanyId,
        billSupplierId,
        treatmentMethodId,
        receiveAddressInfor,
      } = this.orderInfo
      if (this.showBackCompany && !backCompanyId) {
        return this.$message.warning('请选择转回公司');
      }
      if (!orderType) {
        return this.$message.warning('请选择采购订单类型');
      }
      if (!deliveryDemand) {
        return this.$message.warning('请选择发货要求');
      }
      if (!receiveCompanyId) {
        return this.$message.warning('请选择收货公司');
      }
      if (!billSupplierId) {
        return this.$message.warning('无开票供应商，不可下推采购订单');
      }
      if (treatmentMethodId == 18907 && receiveAddressInfor == '') {
        return this.$message.warning('请填写收货地址详情');
      }
      if (!this.settleCompany) {
        return this.$message.warning('请选择结算公司')
      }
      this.pushDownOrder()
    },
    // 定标完成 第二步
    pushDownOrder () {
      const pushDownSubmitData = _.omit(this.orderInfo,
        'winBiddingVOList',
        'freightPayerStr',
        'provinceCode',
        'cityCode',
        'countyCode',
        'areaCode'
      );
      const settleCompany = this.settleCompanyList.find(item => this.settleCompany == item.settlementCompanyId);
      const submitData = {
        ...pushDownSubmitData,
        ...settleCompany,
      }
      this.submitSelfPurchaseOrder(submitData)
    },
    // 自进货订货单下推
    async submitSelfPurchaseOrder (param) {
      const res = await submitSelfPurchaseOrderService(
        param,
        state => { this.submitLoading = state }
      )
      if (res) {
        this.$message.success(res.msg);
        this.purchaseOrderNo = res.data;
        this.successDialogVisible = true;
      }
    },
    limitInput (value, name) {
      this.orderInfo[name] =
        ('' + value) // 第一步：转成字符串
          // eslint-disable-next-line no-useless-escape
          .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
          .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
          .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
          .match(/^\d*(\.?\d{0,2})/g)[0] || ''; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },
  }
};
</script>
<style lang="less">
.push-down-content {
  .operate-area {
    margin: 8px;
  }
}
</style>
